package serviceImpl;

import bean.GroudUser;
import bean.Store;
import bean.Users;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.KeyLengthException;
import mapper.GroudMapper;
import mapper.GroudUserMapper;
import mapper.StoreMapper;
import mapper.UsersMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.LoginRegistrationService;
import util.JwtUtil;
import util.ParameterUtils;
import util.PasswordUtil;
import util.ResponseBean;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Service

public class LoginRegistrationServiceImpl implements LoginRegistrationService {

    private static Logger logger = LoggerFactory.getLogger(LoginRegistrationServiceImpl.class);

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private GroudUserMapper groudUserMapper;

    @Resource
    private StoreMapper storeMapper;

    @Resource
    private GroudMapper groudMapper;

    @Resource
    private ResponseBean responseBean;


    @Override
    public ResponseBean login(String phone, String password) {

        logger.info("进来了登录逻辑层");


        Users users = usersMapper.selectByPhone(phone);

        //账号不存在
        if (users == null) {
            responseBean.setAll(ResponseBean.HTTP_CODE_BAD_REQUEST, "Error In Account Or Password", null);

        } else {
            try {
                //账号状态异常
                if (users.getStatus().equals(ParameterUtils.IS_ENABLED_0)) {
                    responseBean.setAll(ResponseBean.HTTP_CODE_BAD_REQUEST, "Account Expiration Or Freezing", null);

                } else {
                    //匹配密码

                    if (PasswordUtil.getSaltverifyMD5(password,users.getPassword())) {

                        String Identification = users.getIdentification();

                        //groud和store再注册已经处理好了,除非后续更变出现问题，否则不会出现问题
                        String groud = groudMapper.selectByGroud(groudUserMapper.selectByGroudId(users.getUserId()));

                        String store = storeMapper.selectByStoreId(users.getUserId());

                        String token = JwtUtil.creatToken(Identification, groud, store);

                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("Token", token);
                        responseBean.setAll(ResponseBean.HTTP_CODE_OK, "TokenCorrect", hashMap);


                    } else {
                        //密码有误
                        responseBean.setAll(ResponseBean.HTTP_CODE_BAD_REQUEST, "Error In Account Or Password", null);

                    }

                }
            } catch (NullPointerException e) {
                logger.error("-----------秘钥为空异常或者参数为空-----------");
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
                logger.error(e.getMessage());
                e.printStackTrace();

            } catch (KeyLengthException e) {
                logger.error("-----------服务器制作签名异常-----------");
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
                logger.error(e.getMessage());
                e.printStackTrace();

            } catch (JOSEException e) {
                responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
                logger.error("-----------服务器制作签名标识异常-----------");
                logger.error(e.getMessage());
                e.printStackTrace();

            }
        }


        return responseBean;
    }

    @Transactional
    @Override
    public ResponseBean redis(Users users, String code, String codeCache) throws Exception {
        logger.debug("-------------------进来了注册逻辑---------------------");


        //验证码有误
        //从缓存中获取验证码
        if (codeCache.equals("") || codeCache == null) {
            responseBean.setCode(ResponseBean.HTTP_CODE_SYSTEM_ERROR);
            responseBean.setMsg(ResponseBean.MSG_SYSTEM_ERROR_MESSAGE);
            responseBean.setData(null);
        } else if (!code.equals(codeCache)) {
            responseBean.setCode(ResponseBean.HTTP_CODE_BAD_REQUEST);
            responseBean.setMsg("Code Error");
            responseBean.setData(null);
        } else {


            //设置用户ID
            users.setUserId(PasswordUtil.getUUID());

            //对密码加密
            users.setPassword(PasswordUtil.getSaltMD5(users.getPassword()));


            //设置头像 avatar
            users.setAvatar(" 默认头像地址 ");

            //设置状态 status
            users.setStatus(ParameterUtils.IS_ENABLED_1);

            //设置创建时间 create_time
            users.setCreateTime(new Date());

            //设置Identification
            users.setIdentification(PasswordUtil.getUUID());

            //对Store对象操作 默认为买家
            Store store = new Store();
            store.setUserId(users.getUserId());

            //对Groud_User对象操作 默认为普通用户
            GroudUser groudUser = new GroudUser();
            groudUser.setUserId(users.getUserId());

            //等下处理下异常 有可能出现某些数据存在唯一性
            try {
                storeMapper.insertSelective(store);//除了UUID问题，其无问题
                groudUserMapper.insertSelective(groudUser);//除了UUID问题，其无问题
                usersMapper.insert(users);//除了UUID问题 一般只存在手机号码已存在问题

            } catch (DuplicateKeyException e) {
                throw new DuplicateKeyException(e.getMessage());


            } catch (DataIntegrityViolationException e) {
                throw new DataIntegrityViolationException(e.getMessage());

            } catch (Exception e) {
                throw new Exception(e.getMessage());

            }
            responseBean.setAll(ResponseBean.HTTP_CODE_OK, "Log In Yes", null);

        }

        return responseBean;
    }
}
